import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
import json
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, precision_score, recall_score
import xgboost as xgb
import lightgbm as lgb
from sklearn.preprocessing import OneHotEncoder
from sklearn.metrics import confusion_matrix
from sklearn.ensemble import GradientBoostingClassifier
xls = pd.ExcelFile('C:/Users/zlsjBIDF/Downloads/例子.xlsx')
df = pd.read_excel(xls)
column_names = ['landing_type', 'ad_type', 'opt_status','status','delivery_mode','is_comment_disable','status_first', 'ad_download_status', 'show_cnt', 'click_cnt']
data_names = ['landing_type', 'ad_type', 'opt_status','status','delivery_mode','is_comment_disable','status_first', 'ad_download_status']
compute_name = ['show_cnt', 'click_cnt']
df_cleaned = df.dropna(subset=['delivery_setting'])
data = df_cleaned[column_names]
df_encoded = pd.get_dummies(data, columns=data_names)
df_encoded= df_encoded.fillna(0)
compute = df_encoded[compute_name]
compute = compute.values
df_encoded = pd.get_dummies(df_cleaned[data_names],columns=data_names)
data = df_encoded.values
data_deliveries = [json.loads(json_str) for json_str in df_cleaned['delivery_setting'].values]

filtered_keys = ['bid_speed', 'bid_type', 'budget_mode', 'deep_bid_type', 'schedule_type', 'filter_night_switch', 'project_custom', 'budget_optimize_switch']
values_list = []
for i, delivery in enumerate(data_deliveries):
    row_values = []
    for k in filtered_keys:
        if k in delivery:
            row_values.append(delivery[k])
        else:
            # 键不存在时的处理方式，例如使用 None 或者默认值
            row_values.append(None)
    values_list.append(row_values)
y = np.array(values_list)
y = pd.DataFrame(y, columns=['bid_speed', 'bid_type', 'budget_mode', 'deep_bid_type', 'schedule_type', 'filter_night_switch', 'project_custom', 'budget_optimize_switch'])
y = pd.get_dummies(y, columns=['bid_speed', 'bid_type', 'budget_mode', 'deep_bid_type', 'schedule_type', 'filter_night_switch', 'project_custom', 'budget_optimize_switch'])
y = y.values
print(data.shape)
x = np.hstack((data, y))
jisuan = np.empty(49842)
for i in range(49842):
    if compute[i][0] == 0:
        jisuan[i] = 0
    else:
        jisuan[i] = compute[i][1] / compute[i][0]
label = np.empty(49842)
jishu = 0
for z in jisuan:
    if z>0.1 :
        label[jishu]=1
    else:
        label[jishu]=0
    jishu = jishu + 1
print(x.shape)
print(label)
X_train, X_test, y_train, y_test = train_test_split(x, label, test_size=0.2, random_state=42)
param_grid = {
    'n_estimators': [100, 200,300,400,500,600,700,800,900,1000],
}
gbdt = GradientBoostingClassifier(n_estimators=100, random_state=42)
gbdt.fit(X_train, y_train)
# 获取叶子索引
train_leaf_indices = gbdt.apply(X_train)[:, :, 0]
encoder = OneHotEncoder()
train_features_transformed = encoder.fit_transform(train_leaf_indices)
# 对测试集执行相同的 One-Hot 编码
test_leaf_indices = gbdt.apply(X_test)[:, :, 0]
test_features_transformed = encoder.transform(test_leaf_indices)
# 训练逻辑回归模型
lr = LogisticRegression(max_iter=1000)
lr.fit(train_features_transformed, y_train)
# 使用逻辑回归模型进行预测
y_pred = lr.predict(test_features_transformed)
#  评估模型
accuracy = accuracy_score(y_test, y_pred)
print(f'Accuracy: {accuracy,precision_score(y_test, y_pred),recall_score(y_test, y_pred)}')
cm = confusion_matrix(y_test, y_pred)
sns.heatmap(cm, annot=True, fmt='d', cmap='Blues')  # annot=True表示在每个单元格中显示数值
plt.xlabel('Predicted labels')
plt.ylabel('True labels')
plt.title('Confusion Matrix')
plt.show()